package ru.tulupov.producerconsumerpattern;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

public class StatisticManager implements Runnable {
	private static class StatisticManagerHolder {
		public static final StatisticManager INSTANCE = new StatisticManager();
	}

	public static StatisticManager getInstance() {
		return StatisticManagerHolder.INSTANCE;
	}

	private Map<Playable, Integer> map;

	private StatisticManager() {

		map = new HashMap<Playable, Integer>();
		Runtime runtime = Runtime.getRuntime();
		runtime.addShutdownHook(new Thread(this));
	}

	@Override
	public void run() {
		List<Map.Entry<Playable, Integer>> values = new ArrayList<Map.Entry<Playable, Integer>>(
				map.entrySet());
		Collections.sort(values,
				new Comparator<Map.Entry<Playable, Integer>>() {

					@Override
					public int compare(Entry<Playable, Integer> o1,
							Entry<Playable, Integer> o2) {

						return o2.getValue() - o1.getValue();
					}
				});
		for (Map.Entry<Playable, Integer> entry : values) {
			System.out.append(String.format("%s [%d]\n", entry.getKey(),
					entry.getValue()));
		}

	}

	public void update(Map<Playable, Integer> map) {

		Set<Map.Entry<Playable, Integer>> values = map.entrySet();

		for (Map.Entry<Playable, Integer> entry : values) {
			Integer count = this.map.get(entry.getKey());
			if (count != null) {
				this.map.put(entry.getKey(), count + entry.getValue());
			} else {
				this.map.put(entry.getKey(), entry.getValue());
			}
		}
	}

}
